package com.nkzy.controller;

import com.nkzy.domain.User;
import com.nkzy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Create by 王建烨 on 2022/4/15 10:56
 **/

@Controller
@RequestMapping("/users")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public String add(User user,Model model){
        try{
            userService.addUser(user);
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","原因："+e.getMessage());
            model.addAttribute("redirect","/addUser");
            return "error";
        }
        model.addAttribute("msg","注册成功！！！");
        model.addAttribute("redirect","/addUser");
        return "success";
    }

    @PostMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, User user, Model model){
        try {
            user.setId(id);
            userService.update(user);
        }catch (Exception e){
            e.printStackTrace();
            model.addAttribute("msg","原因："+e.getMessage());
            model.addAttribute("redirect","/editUser/"+id);
            return "error";
        }
        model.addAttribute("msg","修改成功！！！");
        model.addAttribute("redirect","/editUser/"+id);
        return "success";
    }

    @GetMapping("/delete/{id}")
    public String edit(@PathVariable Integer id, Model model){
        model.addAttribute("redirect","/userList");
        try{
            userService.delete(id);
        }catch (Exception e){
            model.addAttribute("msg","原因："+e.getMessage());
            return "error";
        }
        model.addAttribute("msg","删除成功！！！");
        return "success";
    }
}
